package com.weasel.security.escape.defaults;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.weasel.core.helper.GodHands;
import com.weasel.security.annotation.SensitiveWordEscape;
import com.weasel.security.escape.EscapeService;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * Created by Dylan on 2015/12/18.
 */
public abstract class AbstractSensitiveWordEscapeService extends AbstractEscapeService{

    protected final Cache<Class<?>,Field[]> classSeen = CacheBuilder.newBuilder().maximumSize(100).build();

    protected String REPLACE = "*";


    @Override
    protected <T> Field[] getEscapeFiles(T obj) {
        try {
            return classSeen.get(obj.getClass(), new Callable<Field[]>() {
                @Override
                public Field[] call() throws Exception {
                    return GodHands.getAnnotaionFields(obj.getClass(), SensitiveWordEscape.class);
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return new Field[]{};
    }

    @Override
    protected String escapeString(String text) {
        Set<String> lexicons = getLexicons();
        for(String lexicon : lexicons){
            text = replaceString(text,lexicon,REPLACE);
        }
        return text;
    }

    /**
     * @param text
     * @param search
     * @param replace
     * @return
     */
    protected String replaceString(String text,String search,String replace){
        return StringUtils.replace(text,search,replace);
    }

    /**
     * @return
     */
    protected abstract Set<String> getLexicons();
}
